package de.sonnemann_it.helden_software.heldenbogen.originalpdf;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class Action {

    private final Communicator communicator;
    private String pluginPath;

    public Action() {
        communicator = new Communicator();
        communicator.getNaechsteAntwort();
    }

    private Document sendAction(final String Action) {
        return sendAction(Action, new HashMap<String, Object>());
    }

    private Document sendAction(String Action, Map<String, Object> params) {
        StringBuilder request = new StringBuilder("<action action=\"");
        request.append(Action).append("\" ");
        for (Entry<String, Object> entry : params.entrySet()) {
            String param = String.format(" %s=\"%s\" ", entry.getKey(), entry.getValue().toString());
            request.append(param);
        }
        request.append(" format=\"xml\" />");
        communicator.sendeAnfrage(request.toString());
        String answer = communicator.getNaechsteAntwort();
        Document doc = null;
        
        DocumentBuilder newDocumentBuilder;
        try {
            
            newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();                   
            
            doc = newDocumentBuilder.parse(
                    new InputSource(new StringReader(answer))
            );
        } catch (Exception ex) {
            Logger.getLogger(Action.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(-1);
        }
                        
        return doc;
        
    }
    
    public Document getHeld(long heldenkey) {
        Document doc = null;
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("heldenkey", heldenkey);
        doc = sendAction("held", params);       
        return doc;
    }
    
    
    public Document getSelectedHeld() {
        Document doc = null;
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("id", "selected");
        doc = sendAction("held", params);       
        return doc;
    }

    public Document getAnzahlHelden() {
        Document doc = sendAction("listHelden");                
        return doc;
    }
    
    public String getPluginPath(){
        if(pluginPath == null){
            Document doc =  sendAction("pluginPfad");
            pluginPath = ((Element)doc.getElementsByTagName("result").item(0)).getAttribute("value");
        }        
        return pluginPath;
    }


}
